<script setup lang="ts">
import type { CaptchaLoginRequest, PasswordLoginRequest, SendSmsRequest } from '@/api/auth'
import { definePage } from '@uni-helper/vite-plugin-uni-pages'
import { onUnmounted, reactive, ref } from 'vue'
import { loginByPassword, loginByPhone, sendSmsCode } from '@/api/auth'
import CaptchaImage from '@/components/CaptchaImage.vue'
import { ResultEnum } from '@/http/tools/enum'
import { useThemeStore } from '@/store/theme'
import { useTokenStore } from '@/store/token'
import { useUserStore } from '@/store/user'
import { tabbarList } from '@/tabbar/config'
import { isPageTabbar } from '@/tabbar/store'
import { ensureDecodeURIComponent, parseUrlToObj } from '@/utils'

// 页面配置
definePage({
  style: {
    // 'custom' 表示开启自定义导航栏，默认 'default'
    navigationStyle: 'custom',
  },
})

// 登录方式枚举
enum LoginType {
  PASSWORD = 'password',
  SMS = 'sms',
}

// 响应式数据
const loginType = ref<LoginType>(LoginType.PASSWORD)
const redirectUrl = ref('')
const loading = ref(false)
const checkKeyImg = ref(0)
const countdown = ref(0)
let timer: any = null

// 验证码组件引用
const captchaComponentRef = ref<InstanceType<typeof CaptchaImage>>()

// 表单数据
const passwordForm = reactive<PasswordLoginRequest>({
  username: 'anshaolong',
  password: 'A@yngyjt@1688',
  captcha: '',
  checkKey: 0,
  systemType: 'mobile',
})

// 为短信验证码添加单独的响应式数据
const smsForm = reactive<CaptchaLoginRequest & { smsCaptcha?: string }>({
  mobile: '',
  captcha: '', // 图形验证码
  captchaImg: '',
  checkKeyImg: 0,
  smsCaptcha: '', // 短信验证码
})

const rememberPassword = ref(false)
// 密码可见性控制
const showPassword = ref(false)

// 状态管理
const tokenStore = useTokenStore()
const userStore = useUserStore()
const themeStore = useThemeStore()

// 页面加载 - 使用function关键字声明以符合ESLint规则
onLoad((options: any) => {
  if (options.redirect) {
    redirectUrl.value = ensureDecodeURIComponent(options.redirect)
  }
  else {
    redirectUrl.value = tabbarList[0].pagePath
  }
  // 读取本地存储的记住密码信息
  const savedUsername = uni.getStorageSync('rememberedUsername')
  const savedPassword = uni.getStorageSync('rememberedPassword')
  if (savedUsername && savedPassword) {
    passwordForm.username = savedUsername
    passwordForm.password = savedPassword
    rememberPassword.value = true
    // 自动切换到密码登录
    loginType.value = LoginType.PASSWORD
  }
  // 验证码由组件自动加载
})

// 切换登录方式
function switchLoginType(type: LoginType) {
  loginType.value = type
  // 移除切换登录方式时重新加载验证码的逻辑
  // 验证码只在页面加载、点击刷新或发送失败时更新
}

// 刷新验证码
function refreshCaptcha() {
  captchaComponentRef.value?.reload()
}

// 处理验证码加载完成
function handleCaptchaLoad(imageSrc: string, checkKey: number) {
  if (loginType.value === LoginType.PASSWORD) {
    passwordForm.checkKey = checkKey
  }
  else {
    checkKeyImg.value = checkKey
    smsForm.checkKeyImg = checkKey
  }
}

// 发送短信验证码
async function sendSms() {
  // 检查是否正在倒计时
  if (countdown.value > 0)
    return

  // 表单验证
  if (!/^1[3-9]\d{9}$/.test(smsForm.mobile)) {
    uni.showToast({ title: '请输入正确的手机号', icon: 'none' })
    return
  }

  if (!smsForm.captcha) {
    uni.showToast({ title: '请输入图形验证码', icon: 'none' })
    return
  }

  try {
    const sendSmsData: SendSmsRequest = {
      userInfo: smsForm.mobile,
      captchaImg: smsForm.captcha,
      checkKeyImg: smsForm.checkKeyImg,
      smsmode: 0,
    }

    const res = await sendSmsCode(sendSmsData)
    if (res.code === -1) {
      uni.showToast({ title: res.data?.message || '发送验证码失败', icon: 'none' })
      throw new Error('发送验证码失败')
    }
    else {
    // 开始倒计时
      countdown.value = 60
      timer = setInterval(() => {
        countdown.value--
        if (countdown.value <= 0) {
          clearInterval(timer)
        }
      }, 1000)

      uni.showToast({ title: '验证码发送成功', icon: 'success' })
    }
  }
  catch (error: any) {
    console.error('发送验证码失败:', error)
    uni.showToast({
      title: error.message || '发送验证码失败，请重试',
      icon: 'none',
    })
    // 发送失败时刷新验证码
    refreshCaptcha()
  }
}

// 页面卸载时清除定时器
onUnmounted(() => {
  if (timer) {
    clearInterval(timer)
  }
})

// 处理密码登录
async function handlePasswordLogin() {
  // 表单验证
  if (!passwordForm.username) {
    uni.showToast({ title: '请输入用户名', icon: 'none' })
    return
  }

  if (!passwordForm.password) {
    uni.showToast({ title: '请输入密码', icon: 'none' })
    return
  }

  if (!passwordForm.captcha) {
    uni.showToast({ title: '请输入验证码', icon: 'none' })
    return
  }

  try {
    loading.value = true

    // 调用登录接口
    const res = await loginByPassword(passwordForm)
    if (res.code !== ResultEnum.Success0) {
      uni.showToast({ title: res?.msg || '登录失败', icon: 'error' })
      return
    }

    // 保存登录信息到状态管理并获取用户信息
    await tokenStore.login(res.data || null)

    // 处理记住密码
    if (rememberPassword.value) {
      uni.setStorageSync('rememberedUsername', passwordForm.username)
      uni.setStorageSync('rememberedPassword', passwordForm.password)
    }
    else {
      uni.removeStorageSync('rememberedUsername')
      uni.removeStorageSync('rememberedPassword')
    }

    uni.showToast({ title: res?.msg || '登录成功', icon: 'success' })

    // 处理跳转
    handleRedirect()
  }
  catch (error: any) {
    console.error('登录失败:', error)
    uni.showToast({
      title: error.message || '登录失败，请重试',
      icon: 'none',
    })
    // 登录失败时刷新验证码
    refreshCaptcha()
  }
  finally {
    loading.value = false
  }
}

// 处理短信登录
async function handleSmsLogin() {
  // 表单验证
  if (!/^1[3-9]\d{9}$/.test(smsForm.mobile)) {
    uni.showToast({ title: '请输入正确的手机号', icon: 'none' })
    return
  }
  if (!smsForm.smsCaptcha) {
    uni.showToast({ title: '请输入短信验证码', icon: 'none' })
    return
  }

  try {
    loading.value = true

    // 构建登录参数，将短信验证码传递给登录接口
    const loginParams = {
      ...smsForm,
      captcha: smsForm.smsCaptcha, // 使用短信验证码进行登录
    }
    // 调用登录接口
    const res = await loginByPhone(loginParams)
    if (res.code !== ResultEnum.Success0) {
      uni.showToast({ title: res?.msg || '登录失败', icon: 'error' })
      return
    }
    // 保存登录信息到状态管理并获取用户信息
    await tokenStore.login(res.data || null)

    uni.showToast({ title: '登录成功', icon: 'success' })

    // 处理跳转
    handleRedirect()
  }
  catch (error: any) {
    console.error('登录失败:', error)
    uni.showToast({
      title: error.message || '登录失败，请重试',
      icon: 'none',
    })
    // 登录失败时刷新验证码
    refreshCaptcha()
  }
  finally {
    loading.value = false
  }
}

// 处理跳转
function handleRedirect() {
  let path = redirectUrl.value
  if (!path.startsWith('/')) {
    path = `/${path}`
  }

  const { path: _path } = parseUrlToObj(path)

  if (isPageTabbar(_path)) {
    uni.switchTab({ url: path })
  }
  else {
    uni.redirectTo({ url: path })
  }
}
</script>

<template>
  <view :class="[themeStore.theme === 'light' ? 'bg-white' : 'bg-gray-900']" class="min-h-screen flex flex-col items-center px-6 py-10 transition-all duration-300">
    <!-- Logo区域 -->
    <view class="mb-8 mt-4 text-center">
      <image src="/static/logo.png" class="mx-auto mb-2 h-16 w-16 rounded-lg" mode="aspectFit" />
      <view class="text-xl font-bold" :class="themeStore.theme === 'light' ? 'text-gray-800' : 'text-white'">
        钢友移动审批
      </view>
    </view>

    <!-- 登录表单 -->
    <view class="max-w-xs w-full">
      <!-- 登录表单容器 -->
      <template v-if="loginType === LoginType.PASSWORD">
        <!-- 用户名 -->
        <view class="mb-5">
          <text
            class="mb-2 block text-sm font-medium"
            :class="themeStore.theme === 'light' ? 'text-gray-600' : 'text-gray-300'"
          >
            用户名
          </text>
          <view
            class="flex items-center rounded-lg px-4 py-3"
            :class="themeStore.theme === 'light' ? 'bg-gray-100' : 'bg-gray-800'"
          >
            <input
              v-model="passwordForm.username"
              type="text"
              placeholder="请输入用户名"
              class="flex-1 bg-transparent text-base"
              :class="themeStore.theme === 'light' ? 'text-gray-800' : 'text-white'"
              :placeholder-class="themeStore.theme === 'light' ? 'text-gray-400' : 'text-gray-500'"
              :disabled="loading"
            >
          </view>
        </view>

        <!-- 密码 -->
        <view class="mb-5">
          <text
            class="mb-2 block text-sm font-medium"
            :class="themeStore.theme === 'light' ? 'text-gray-600' : 'text-gray-300'"
          >
            密码
          </text>
          <view
            class="flex items-center rounded-lg px-4 py-3"
            :class="themeStore.theme === 'light' ? 'bg-gray-100' : 'bg-gray-800'"
          >
            <input
              v-model="passwordForm.password"
              :type="!showPassword ? 'text' : 'safe-password'"
              :password="!showPassword"
              placeholder="请输入密码"
              adjust-position
              class="flex-1 bg-transparent text-base"
              :class="themeStore.theme === 'light' ? 'text-gray-800' : 'text-white'"
              :placeholder-class="themeStore.theme === 'light' ? 'text-gray-400' : 'text-gray-500'"
              :disabled="loading"
            >
            <!-- 密码可见性切换按钮 -->
            <view class="ml-2 cursor-pointer" @tap="showPassword = !showPassword">
              <i class="text-xl c-gray-500" :class="showPassword ? 'i-solar:eye-broken' : 'i-solar:eye-closed-broken'" />
            </view>
          </view>
        </view>

        <!-- 验证码 -->
        <view class="mb-5">
          <text
            class="mb-2 block text-sm font-medium"
            :class="themeStore.theme === 'light' ? 'text-gray-600' : 'text-gray-300'"
          >
            图形验证码
          </text>
          <view class="flex space-x-3">
            <view
              class="flex flex-1 items-center rounded-lg px-4 py-3"
              :class="themeStore.theme === 'light' ? 'bg-gray-100' : 'bg-gray-800'"
            >
              <input
                v-model="passwordForm.captcha"
                type="text"
                placeholder="请输入验证码"
                class="flex-1 bg-transparent text-base"
                :class="themeStore.theme === 'light' ? 'text-gray-800' : 'text-white'"
                :placeholder-class="themeStore.theme === 'light' ? 'text-gray-400' : 'text-gray-500'"
                :disabled="loading"
              >
            </view>
            <captcha-image
              ref="captchaComponentRef"
              height="h-11"
              :disabled="loading"
              @load="handleCaptchaLoad"
              @update:check-key="(key) => { passwordForm.checkKey = key }"
            />
          </view>
        </view>
      </template>

      <!-- 短信登录表单 - 仅在选择短信登录时显示 -->
      <template v-else-if="loginType === LoginType.SMS">
        <!-- 手机号 -->
        <view class="mb-5">
          <text
            class="mb-2 block text-sm font-medium"
            :class="themeStore.theme === 'light' ? 'text-gray-600' : 'text-gray-300'"
          >
            手机号
          </text>
          <view
            class="flex items-center rounded-lg px-4 py-3"
            :class="themeStore.theme === 'light' ? 'bg-gray-100' : 'bg-gray-800'"
          >
            <input
              v-model="smsForm.mobile"
              type="digit"
              placeholder="请输入手机号"
              class="flex-1 bg-transparent text-base"
              :class="themeStore.theme === 'light' ? 'text-gray-800' : 'text-white'"
              :placeholder-class="themeStore.theme === 'light' ? 'text-gray-400' : 'text-gray-500'"
              :maxlength="11"
              :disabled="loading"
            >
          </view>
        </view>

        <!-- 图形验证码 -->
        <view class="mb-5">
          <text
            class="mb-2 block text-sm font-medium"
            :class="themeStore.theme === 'light' ? 'text-gray-600' : 'text-gray-300'"
          >
            图形验证码
          </text>
          <view class="flex space-x-3">
            <view
              class="flex flex-1 items-center rounded-lg px-4 py-3"
              :class="themeStore.theme === 'light' ? 'bg-gray-100' : 'bg-gray-800'"
            >
              <input
                v-model="smsForm.captcha"
                type="text"
                placeholder="请输入图形验证码"
                class="flex-1 bg-transparent text-base"
                :class="themeStore.theme === 'light' ? 'text-gray-800' : 'text-white'"
                :placeholder-class="themeStore.theme === 'light' ? 'text-gray-400' : 'text-gray-500'"
                :disabled="loading"
              >
            </view>
            <captcha-image
              ref="captchaComponentRef"
              height="h-11"
              :disabled="loading"
              @load="handleCaptchaLoad"
              @update:check-key="(key) => { smsForm.checkKeyImg = key }"
            />
          </view>
        </view>

        <!-- 短信验证码 -->
        <view class="mb-5">
          <text
            class="mb-2 block text-sm font-medium"
            :class="themeStore.theme === 'light' ? 'text-gray-600' : 'text-gray-300'"
          >
            短信验证码
          </text>
          <view class="flex space-x-3">
            <view
              class="flex flex-1 items-center rounded-lg px-4 py-3"
              :class="themeStore.theme === 'light' ? 'bg-gray-100' : 'bg-gray-800'"
            >
              <input
                v-model="smsForm.smsCaptcha"
                type="text"
                placeholder="请输入短信验证码"
                class="flex-1 bg-transparent text-base"
                :class="themeStore.theme === 'light' ? 'text-gray-800' : 'text-white'"
                :placeholder-class="themeStore.theme === 'light' ? 'text-gray-400' : 'text-gray-500'"
              >
            </view>
            <view
              size="mini"
              class="h-11 center rounded px-4 text-sm font-medium transition-colors duration-200"
              :disabled="loading || countdown > 0"
              :class="[countdown > 0 ? 'text-gray-400' : 'text-blue-600', themeStore.theme === 'light' ? 'bg-blue-50 text-blue-600' : 'bg-blue-900/30 text-blue-400']"
              @click="sendSms"
            >
              {{ countdown > 0 ? `${countdown}秒后重发` : '获取验证码' }}
            </view>
          </view>
        </view>
      </template>

      <!-- 记住密码 -->
      <template v-if="loginType === LoginType.PASSWORD">
        <view class="mb-8 flex items-center">
          <checkbox
            :checked="rememberPassword"
            :disabled="loading"
            class="text-blue-600"
            @change="rememberPassword = $event.detail.value"
          />
          <text
            class="ml-2 text-sm"
            :class="themeStore.theme === 'light' ? 'text-gray-600' : 'text-gray-300'"
          >
            记住密码
          </text>
        </view>
      </template>

      <!-- 登录按钮 -->
      <button
        class="w-full rounded-lg bg-blue-600 py-3 text-base text-white font-medium transition-all duration-300 active:scale-98"
        :class="{ 'opacity-60 cursor-not-allowed': loading }"
        :loading="loading"
        @click="loginType === LoginType.PASSWORD ? handlePasswordLogin() : handleSmsLogin()"
      >
        登录
      </button>

      <!-- 登录方式切换按钮 -->
      <view class="mb-2 mt-6 flex justify-center">
        <view
          class="flex items-center justify-center rounded-full px-6 py-3 text-sm font-medium transition-all duration-300 active:scale-95 space-x-2"
          :class="themeStore.theme === 'light' ? 'bg-blue-50 text-blue-600' : 'bg-blue-900/30 text-blue-400'"
          :disabled="loading"
          @click="switchLoginType(loginType === LoginType.PASSWORD ? LoginType.SMS : LoginType.PASSWORD)"
        >
          <i :class="loginType === LoginType.PASSWORD ? 'i-solar:shield-check-broken' : 'i-solar:lock-keyhole-minimalistic-broken'" />
          <text>
            {{ loginType === LoginType.PASSWORD ? '验证码登录' : '密码登录' }}
          </text>
        </view>
      </view>
    </view>
  </view>
</template>

<style scoped>
/* 使用UnoCSS原子化类名，这里只保留必要的全局样式覆盖 */
input {
  font-size: 16px;
}

:deep(.uni-input-placeholder) {
  color: var(--placeholder-color, #999999);
}

:deep(.uni-checkbox-input-checked) {
  background-color: #1677ff !important;
  border-color: #1677ff !important;
}

:deep(input:focus) {
  outline: none;
}
</style>
